# -*- coding: utf-8 -*-
#
# Copyright (C) 2011  Benjamin Heil
#
# This file is part of Feedmail.
#
# Feedmail is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.conf import settings
from django.core import mail
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

from feedmanager.models import FeedItem, FeedAbo, FeedData
from feedmail_cron import send_feed_gone_mail, send_new_location_mail, run_cron
from account.tests import add_testuser

class TestFeedmailCron(TestCase):

    def runTest(self):
        self.test_send_feed_gone_mail()
        self.test_send_new_location_mail()
        self.test_run_cron()

    def setUp(self):
        """Adds a test user and creates abos for some feeds."""
        add_testuser(self, username='testmanager_user', password='password', mail='testmanager_user@bheil.net')
        login = self.client.login(username='testmanager_user', password='password')
        self.failUnless(login, 'Could not log in')

        # Add some feeds with unicode-chars like japanese, french etc.
        url = reverse('feedmanager_add_feed')
        # german
        response = self.client.post(url, {'url': 'http://www.spiegel.de/schlagzeilen/index.rss'})
        self.assertEqual(response.status_code, 200)
        # arabic
        response = self.client.post(url, {'url': 'http://www.aljazeera.net/AljazeeraRss/Rss.aspx?URL=RSS-Portal.xml'})
        self.assertEqual(response.status_code, 200)
        # japan
        response = self.client.post(url, {'url': 'http://mainichi.pheedo.jp/f/mainichijp_flash'})
        self.assertEqual(response.status_code, 200)

    def test_send_new_location_mail(self):
        mail.outbox = []
        feeds = FeedItem.objects.all()
        for feed in feeds:
            send_new_location_mail(feed, feed.url)
        self.assertEquals(len(mail.outbox), len(feeds))

    def test_send_feed_gone_mail(self):
        mail.outbox = []
        feeds = FeedItem.objects.all()
        for feed in feeds:
            send_feed_gone_mail(feed)
        self.assertEquals(len(mail.outbox), len(feeds))

    def test_run_cron(self):
        """Just run the normal cron job."""
        mail.outbox = []
        # Clear FeedData - all items will be fetched and mails will be generated
        FeedData.objects.all().delete()
        run_cron()
        self.assertTrue(len(mail.outbox) > 0)
